<?php

namespace app\award;

use app\controllers\h5\uni\HomeController;
use app\models\AdminSupplier;
use app\models\AwardList;
use app\models\AwardResult;
use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\Queue;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\user\UserScoreTicket;
use app\models\UserBalance;
use app\models\UserStore;
use app\models\UserStoreLog;
use app\models\VipCardLog;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class Award
{
    protected $user;
    protected $order;
    protected $set;

    protected $items;

    // 总金额
    protected $amount;

    protected $is_bao = false;
    protected $is_buy = false;
    protected $is_express = false;

    // 是否为重算订单
    protected $is_reset = false;


    public function __construct(Order $order, $is_reset = false)
    {

        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);
        $this->set = SetUserUp::getLastOne();

        $this->is_reset = $is_reset;

        $this->items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        // 复购商品价格
        $this->price = Product::find()
            ->select(['price'])
            ->where(['id' => $product_id])
            ->scalar();

        $this->amount = $this->order->total_pay - $this->order->total_freight;



        // 会员卡
        $this->is_bao = ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT']);

        // 商品
        $this->is_buy = ProductAreaList::checkInArea($product_id, Product::$areaMap['BUY']);

        // 快递
        $this->is_express = $this->order->express_area == 1;

        // 返佣[推荐与团队奖]
        $this->recommend();

        // 区域奖
        $this->area();

        // 如果是会员卡, 直接完成订单状态
        if ($this->is_bao) {
            $this->order->status = Order::$statusMapping['FINISH'];
            $this->order->save();

            // 记录优惠券与购物券日志
            $log = new VipCardLog();
            $log->user_id = $this->user->id;
            $log->order_id = $this->order->id;
            $log->ticket = $this->set->card_amount * $this->set->card_num;
            $log->platform_ticket = $this->set->card_platform_ticket;
            $log->save();

            // 帐户
            $account = UserAccount::findOne(['user_id' => $this->user->id]);
            $account->ticket += $this->set->card_amount * $this->set->card_num;
            $account->platform_ticket += $this->set->card_platform_ticket;
            $account->save();
        }

    }

    private function recommend()
    {
        $chain = Chain::getReferrerChain($this->order->user_id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3'],
            UserLevel::$keys['vip4'],
        ], true);

        $has_vip1 = false;
        $has_vip2 = false;
        // $has_vip2_team = false;
        $has_vip3 = false;
        $has_vip4 = false;

        $vip1 = $this->getCommission('vip1');
        $vip2 = $this->getCommission('vip2');
        // $vip2_team = $this->getCommission('vip2_team');
        $vip3 = $this->getCommission('vip3');
        $vip4 = $this->getCommission('vip4');

        // var_dump($chain);exit;

        foreach ($chain as $user) {
            if ((!$has_vip1 && !$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip1']) {
                $commission = $vip1;
                $this->saveCommission($user->id, $commission, 11, 'VIP推荐奖');
                $has_vip1 = true;
            }
            if ((!$has_vip2 && !$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip2']) {
                $commission = $vip2;
                if (!$has_vip1) {
                    $commission += $vip1;
                }
                $this->saveCommission($user->id, $commission, 12, 'SVIP推荐奖');
                // $this->saveCommission($user->id, $vip2_team, 22, 'SVIP团队奖');
                $has_vip2 = true;
            }
            if ((!$has_vip3 && !$has_vip4) && $user->level == UserLevel::$keys['vip3']) {
                $commission = $vip3;
                if (!$has_vip2) {
                    $commission += $vip2;
                    if (!$has_vip1) {
                        $commission += $vip1;
                    }
                }
                $this->saveCommission($user->id, $commission, 13, '市代推荐奖');
                $has_vip3 = true;
            }
            if ((!$has_vip4) && $user->level == UserLevel::$keys['vip4']) {
                $commission = $vip4;
                if (!$has_vip3) {
                    $commission += $vip3;
                    if (!$has_vip2) {
                        $commission += $vip2;
                        if (!$has_vip1) {
                            $commission += $vip1;
                        }
                    }
                }
                $this->saveCommission($user->id, $commission, 14, '省代推荐奖');
                $has_vip4 = true;
                break;
            }
        }
    }

    private function area()
    {
        // $address = UserAddress::findOne(['id' => $this->order->user_address]);

        // 补运费, 还要处理下地址
        // var_dump($this->order);exit;
        if ($this->order->total_quantity == 0) {
            $o = $this->order->request_params;
            if ($o) {
                $o = json_decode($o, true);
                if ($o['order_id']) {
                    $x = Order::find()
                        ->where(['id' => $o['order_id']])
                        ->select(['send_address'])
                        ->scalar();
                    $this->order->send_address = $x;
                    $this->order->save();
                }
            }
        }

        // 02-16 改成了寄件地址
        // 这样普通商品, 就没有这个奖了, 这个已经沟通过的
        $address = UserAddress::findOne(['id' => $this->order->send_address]);

        if (!$address) {
            return;
        }

        $vip3 = User::findOne(['address_up' => $address->city_id]);
        $vip4 = User::findOne(['address_up' => $address->province_id]);

        if ($vip3) {
            $commission = $this->getCommission('vip3_area');
            $this->saveCommission($vip3->id, $commission, 101, '市代地区奖');
        }
        if ($vip4) {
            $commission = $this->getCommission('vip4_area');
            // if ($vip3) {
            //     $commission -= $this->getCommission('vip3_area');
            // }
            $this->saveCommission($vip4->id, $commission, 102, '省代地区奖');
        }
    }

    // 获取对应的佣金
    // 由于卡片区是根据固定金额来的, 但是已经限制数量了
    // 商品与快递区是根据百分比来的, 所以不用处理数量
    private function getCommission($key)
    {
        $c = 0;
        $amount = $this->order->total_pay - $this->order->total_freight;

        if ($this->is_express) {
            if ($key == 'vip1') {
                $c = $this->set->express_vip1 / 100 * $amount;
            }
            if ($key == 'vip2') {
                $c = $this->set->express_vip2 / 100 * $amount;
            }
            if ($key == 'vip3') {
                $c = $this->set->express_vip3 / 100 * $amount;
            }
            if ($key == 'vip4') {
                $c = $this->set->express_vip4 / 100 * $amount;
            }
            if ($key == 'vip2_team') {
                // VIP1的收益
                // $c = $this->set->express_vip2_team / 100 * $this->set->express_vip1;
            }
            if ($key == 'vip3_area') {
                // VIP + SVIP + SVIP团队
                // $c = $this->set->express_vip3_area / 100
                //     * ($this->set->express_vip1 + $this->set->express_vip2
                //         + ($this->set->express_vip2_team / 100 * $this->set->express_vip1));

                $c = $this->set->express_vip3_area / 100 * $amount;
            }
            if ($key == 'vip4_area') {
                // VIP + SVIP + SVIP团队, 写奖的时候, 需要处理极差
                // $c = $this->set->express_vip4_area / 100
                //     * ($this->set->express_vip1 + $this->set->express_vip2
                //         + ($this->set->express_vip2_team / 100 * $this->set->express_vip1));

                $c = $this->set->express_vip4_area / 100 * $amount;
            }
        }

        if ($this->is_bao) {
            if ($key == 'vip1') {
                $c = $this->set->card_vip1 / 100 * $amount;
            }
            if ($key == 'vip2') {
                $c = $this->set->card_vip2 / 100 * $amount;
            }
            if ($key == 'vip3') {
                $c = $this->set->card_vip3 / 100 * $amount;
            }
            if ($key == 'vip4') {
                $c = $this->set->card_vip4 / 100 * $amount;
            }
            if ($key == 'vip2_team') {
                // $c = $this->set->card_vip2_team / 100 * ($this->set->card_vip1 / 100 * $amount);
            }
            if ($key == 'vip3_area') {
                // $c = $this->set->card_vip3_area / 100
                //     * (($this->set->card_vip1 / 100 * $amount)
                //         + ($this->set->card_vip2 / 100 * $amount)
                //         + ($this->set->card_vip2_team / 100 * ($this->set->card_vip1 / 100 * $amount)));
                $c = $this->set->card_vip3_area / 100 * $amount;
            }
            if ($key == 'vip4_area') {
                // $c = $this->set->card_vip4_area / 100
                //     * (($this->set->card_vip1 / 100 * $amount)
                //         + ($this->set->card_vip2 / 100 * $amount)
                //         + ($this->set->card_vip2_team / 100 * ($this->set->card_vip1 / 100 * $amount)));
                $c = $this->set->card_vip4_area / 100 * $amount;
            }
        }

        if ($this->is_buy) {
            if ($key == 'vip1') {
                $c = $this->set->product_vip1 / 100 * $amount;
            }
            if ($key == 'vip2') {
                $c = $this->set->product_vip2 / 100 * $amount;
            }
            if ($key == 'vip3') {
                $c = $this->set->product_vip3 / 100 * $amount;
            }
            if ($key == 'vip4') {
                $c = $this->set->product_vip4 / 100 * $amount;
            }
            if ($key == 'vip2_team') {
                // $c = $this->set->product_vip2_team / 100 * ($this->set->product_vip1 / 100 * $amount);
            }
            if ($key == 'vip3_area') {
                // $c = $this->set->product_vip3_area / 100
                //     * (($this->set->product_vip1 / 100 * $amount)
                //         + ($this->set->product_vip2 / 100 * $amount)
                //         + ($this->set->product_vip2_team / 100 * ($this->set->product_vip1 / 100 * $amount)));

                $c = $this->set->product_vip3_area / 100 * $amount;
            }
            if ($key == 'vip4_area') {
                // $c = $this->set->product_vip4_area / 100
                //     * (($this->set->product_vip1 / 100 * $amount)
                //         + ($this->set->product_vip2 / 100 * $amount)
                //         + ($this->set->product_vip2_team / 100 * ($this->set->product_vip1 / 100 * $amount)));

                $c = $this->set->product_vip4_area / 100 * $amount;
            }
        }

        // var_dump($this->order->total_quantity);exit;


        return $c;
    }


    // 保存佣金 (await balance)
    protected function saveCommission($user_id, $balance, $type, $name, $status = 0)
    {
        if ($balance >= 0.01) {

            // 补运费, 改成已返
            if ($this->order->total_quantity == 0) {
                $status = 1;
            }

            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();
            $account = UserAccount::findOne(['user_id' => $user_id]);

            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }

              $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, '返佣', $this->order->id);
            }

            return true;
        }
    }

}